import 'dart:convert' show json;
import 'package:loxen/api/api.dart';
import 'package:loxen/api/http_util.dart';

mixin SendEmailMixin {
  void sendEmail(String email, String id,
      {Function() onSuccess, Function(String msg) onError}) {
    ApiService.sendEmail(email, id).listen((event) {
      if (onSuccess != null) onSuccess.call();
    }, onError: (error, stack) {
      if (error is ServiceException) {
        var data = Root.fromJson(error.data);
        var email = data.data.email;
        var id = data.data.hs_id;
        if (email != null && email.length > 0) {
          if (onError != null) onError.call(email[0]);
          return;
        }
        if (id != null && id.length > 0) {
          if (onError != null) onError.call(id[0]);
          return;
        }
      } else {
        if (onError != null) onError.call('网络异常');
      }
    });
  }
}

T asT<T>(dynamic value) {
  if (value is T) {
    return value;
  }

  return null;
}

class Root {
  Root({
    this.code,
    this.data,
  });

  factory Root.fromJson(Map<String, dynamic> jsonRes) => jsonRes == null
      ? null
      : Root(
          code: asT<int>(jsonRes['code']),
          data: Send.fromJson(asT<Map<String, dynamic>>(jsonRes['data'])),
        );

  int code;
  Send data;

  Map<String, dynamic> toJson() => <String, dynamic>{
        'code': code,
        'data': data,
      };

  @override
  String toString() {
    return json.encode(this);
  }
}

class Send {
  Send({
    this.email,
    this.hs_id,
  });

  factory Send.fromJson(Map<String, dynamic> jsonRes) {
    if (jsonRes == null) {
      return null;
    }

    final List<String> email = jsonRes['email'] is List ? <String>[] : null;
    if (email != null) {
      for (final dynamic item in jsonRes['email']) {
        if (item != null) {
          email.add(asT<String>(item));
        }
      }
    }

    final List<String> hs_id = jsonRes['hs_id'] is List ? <String>[] : null;
    if (hs_id != null) {
      for (final dynamic item in jsonRes['hs_id']) {
        if (item != null) {
          hs_id.add(asT<String>(item));
        }
      }
    }
    return Send(
      email: email,
      hs_id: hs_id,
    );
  }

  List<String> email;
  List<String> hs_id;

  Map<String, dynamic> toJson() => <String, dynamic>{
        'email': email,
        'hs_id': hs_id,
      };

  @override
  String toString() {
    return json.encode(this);
  }
}
